# coding=utf-8
import arcpy

tl = r'E:\workData\20230825岸线规划\易日沟\DLG\2年线.shp'


def query_l_length(poline_file):
    """
    :param poline_file: 线shp文件
    :return:
    """
    cs = arcpy.da.SearchCursor(poline_file, 'SHAPE@')
    ls = [row[0] for row in cs]
    for l in ls:
        print l.length, l.pointCount


def check_multyPart(polyLine_file):
    cs = arcpy.da.SearchCursor(polyLine_file, 'SHAPE@')
    ls = [row[0] for row in cs]
    for l in ls:
        if l.isMultipart:
            print "isMultipart"
        else:
            print "OK"


def calculate_pl_length_WGS84(polyLine_file):
    cs = arcpy.da.SearchCursor(polyLine_file, 'SHAPE@')
    ls = [row[0] for row in cs]
    ds = arcpy.Describe(polyLine_file).extent
    xmin = ds.XMin
    xmax = ds.XMax
    xz = (xmax + xmin) / 2
    if xz > 97.5 and xz < 100.5:
        for l in ls:
            print "99带：{}".format(l.projectAs(arcpy.SpatialReference(4542)).length)
    elif xz > 100.5 and xz < 103.5:
        for l in ls:
            print "102带：{}".format(l.projectAs(arcpy.SpatialReference(4543)).length)
    elif xz > 103.5 and xz < 106.5:
        for l in ls:
            print "105带：{}".format(l.projectAs(arcpy.SpatialReference(4544)).length)
    else:
        print  "非地理坐标系文件"


def extract_by_part_emptyFields(shpFile, shpName, ext_path):
    """
    将包含多个要素的shp文件释放为单个的文件，没有属性字段
    :param shpFile: 总的shp文件
    :param shpName: 提取出的文件命名前辍like:XX村_001
    :param ext_path: 释放的地址
    :return:
    """
    shapeType = arcpy.Describe(shpFile).shapeType
    cs = arcpy.da.SearchCursor(shpFile, 'SHAPE@')
    pls = [row[0] for row in cs]
    i = 1
    for pl in pls:
        aL = arcpy.CreateFeatureclass_management(
            ext_path,
            '{}{:03}.shp'.format(shpName, i),
            shapeType)
        cs = arcpy.da.InsertCursor(aL, ['SHAPE@'])
        cs.insertRow([pl])
        i += 1


def extract_by_part_withFields(shpFile, ext_path):
    """
    将包含多个要素的shp文件释放为单个的文件,包含属性字段
    :param shpFile: 总的shp文件
    :param ext_path: 释放的地址
    :return:
    """
    fileName = arcpy.Describe(shpFile).baseName.encode('utf-8')
    cs = arcpy.da.SearchCursor(shpFile, ['SHAPE@', '*'])
    shpDatasList = [row for row in cs]
    i = 1
    for data in shpDatasList:
        aL = arcpy.CreateFeatureclass_management(
            ext_path,
            '{}{:03}.shp'.format(fileName, i),
            template=shpFile)
        cs = arcpy.da.InsertCursor(aL, ['SHAPE@', '*'])
        cs.insertRow(data)
        i += 1

def extract_FromMDBs(mdbsPath, featureName):
    """
    根据分幅MDB提取各层要素,设置env环境，不要M值和Z值
    :param mdbsPath: mdb文件夹（单层，只有mdb文件）
    :param featureName: 要素名称（'TERL','HYDA')等
    :return:
    """
    arcpy.env.workspace = mdbsPath
    arcpy.env.overwriteOutput = True
    arcpy.env.outputMFlag = "Disabled"
    arcpy.env.outputZFlag = "Disabled"
    mdbs = arcpy.ListFiles('*.mdb')
    arcpy.CreateFolder_management(mdbsPath, 'single')
    arcpy.CreateFolder_management(mdbsPath, 'merge')
    shps = []
    for mdb in mdbs:
        print mdb
        shp = mdbsPath.decode('utf-8') + '\\' + mdb + '\\' + 'DLG' + '\\' + featureName
        tempshpname = arcpy.Describe(mdb).name.replace('-', '').replace('.mdb', '') + arcpy.Describe(shp).name + '.shp'
        shp2 = arcpy.FeatureClassToFeatureClass_conversion(shp, mdbsPath + '\\' + 'single', tempshpname)
        arcpy.AddField_management(shp2, 'FileName', 'TEXT')
        arcpy.CalculateField_management(shp2, 'FileName', '"{}"'.format(mdb.encode('utf-8')))
        shps.append(shp2)
    arcpy.Merge_management(shps, mdbsPath + '\\' + 'merge' + '\\' + '{}.shp'.format((featureName)))


def extract_FromMDBs_queryByField(mdbsPath, featureName, expression):
    """
    根据分幅MDB提取各层要素并根据字段内容筛选
    :param mdbsPath: mdb文件夹（单层，只有mdb文件）
    :param featureName: 要素名称（'TERL','HYDA')等
    :param expression: 字段内容过滤(like 'GB = 210100')
    :return:
    """
    arcpy.env.workspace = mdbsPath
    arcpy.env.overwriteOutput = True
    mdbs = arcpy.ListFiles('*.mdb')
    arcpy.CreateFolder_management(mdbsPath, 'single')
    arcpy.CreateFolder_management(mdbsPath, 'merge')
    shps = []
    for mdb in mdbs:
        print mdb
        shp = mdbsPath.decode('utf-8') + '\\' + mdb + '\\' + 'DLG' + '\\' + featureName
        tempshpname = arcpy.Describe(mdb).name.replace('-', '').replace('.mdb', '') + arcpy.Describe(shp).name + '.shp'
        shp2 = arcpy.FeatureClassToFeatureClass_conversion(shp, mdbsPath + '\\' + 'single', tempshpname,
                                                           where_clause=expression)
        shps.append(shp2)
    arcpy.Merge_management(shps, mdbsPath + '\\' + 'merge' + '\\' + '{}.shp'.format((featureName)))
def zxToKilometerPoint(zx):
    """
    :param zx: 中线线文件,名称为：河流名称+中线（洪河中线）
    :return:按整公里生成的点文件(直接投影为WGS84坐标系)
    """
    arcpy.env.overwriteOutput = True
    path = arcpy.Describe(zx).path
    riverName = arcpy.Describe(zx).baseName.replace('中线'.decode('utf-8'),'')
    wikd = arcpy.Describe(zx).spatialReference.factoryCode
    cs = arcpy.da.SearchCursor(zx, 'SHAPE@')
    zxShape = [row[0] for row in cs][0]
    zxLen = zxShape.length
    KpList = []
    i = 0
    while i < zxShape.length:
        name = 'K' + str(i / 1000)
        Kp = row[0].positionAlongLine(i).projectAs(arcpy.SpatialReference(4326))
        cn = [name, Kp]
        KpList.append(cn)
        print 'K' + str(i / 1000), row[0].positionAlongLine(i).centroid.X, row[
            0].positionAlongLine(
            i).centroid.Y
        i += 1000
    lastPName = 'K{}'.format(int(zxLen/1000)) + '+' + '{}'.format(int(zxLen%1000))
    print lastPName
    lastP = zxShape.lastPoint #point类型
    lastPG = arcpy.PointGeometry(lastP,arcpy.SpatialReference(wikd)) #PointGeometry类型
    lastPShapeProjShape = lastPG.projectAs(arcpy.SpatialReference(4326))

    lpcn = [lastPName,lastPShapeProjShape]
    KpList.append(lpcn)
    p = arcpy.CreateFeatureclass_management(path, '{}公里桩'.format(riverName.encode('utf-8')), 'POINT', spatial_reference=arcpy.SpatialReference(4326))
    arcpy.AddField_management(p, '里程', 'TEXT')
    yb = arcpy.da.InsertCursor(p, ['里程', 'SHAPE@'])
    for cn in KpList:
        yb.insertRow(cn)
    del yb
def clearMetaData(dirPath):
    """
    删除元数据指定字段信息
    :param dirPath:
    :return:
    """
    import os
    metaDataList = []
    for i, v, m in os.walk(dirPath.decode('utf-8')):
        for a in m:
            if 'DOM.mdb' in a:
                table = os.path.join(i, a) + '\\DOM元数据'.decode('utf-8')
                metaDataList.append(table)
            elif 'DEM.mdb' in a:
                table = os.path.join(i, a) + '\\DEM元数据'.decode('utf-8')
                metaDataList.append(table)
            elif 'DLG.mdb' in a:
                table = os.path.join(i, a) + '\\DLG元数据'.decode('utf-8')
                metaDataList.append(table)

    for metaData in metaDataList:
        print metaData;
        metaDataType = metaData.split('\\')[-1]
        if (metaDataType == 'DOM元数据'.decode('utf-8')):
            with arcpy.da.UpdateCursor(metaData, ['*']) as yb:
                for row in yb:
                    prName = row[0].encode('utf-8').replace('四川省河湖管理范围划定', '')
                    row[0] = prName
                    row[2] = ''
                    row[3] = ''
                    row[4] = ''
                    row[16] = ''
                    yb.updateRow(row)
        elif (metaDataType == 'DEM元数据'.decode('utf-8')):
            with arcpy.da.UpdateCursor(metaData, ['*']) as yb:
                for row in yb:
                    prName = row[0].encode('utf-8').replace('四川省河湖管理范围划定', '')
                    row[0] = prName
                    row[7] = ''
                    row[8] = ''
                    row[9] = ''
                    row[39] = ''
                    row[45] = ''
                    yb.updateRow(row)
        elif (metaDataType == 'DLG元数据'.decode('utf-8')):
            with arcpy.da.UpdateCursor(metaData, ['*']) as yb:
                for row in yb:
                    prName = row[0].encode('utf-8').replace('四川省河湖管理范围划定', '')
                    row[0] = prName
                    row[9] = ''
                    row[10] = ''
                    row[11] = ''
                    row[36] = ''
                    row[42] = ''
                    yb.updateRow(row)
def metaDataToExcel(dirPath):
    """
    读取元数据至excel文档
    :param dirPath:
    :return:
    """
    import pandas as pd
    import os
    metaDataList = []
    for i, v, m in os.walk(dirPath.decode('utf-8')):
        for a in m:
            if 'DOM.mdb' in a:
                table = os.path.join(i, a) + '\\DOM元数据'.decode('utf-8')
                metaDataList.append(table)
            elif 'DEM.mdb' in a:
                table = os.path.join(i, a) + '\\DEM元数据'.decode('utf-8')
                metaDataList.append(table)
            elif 'DLG.mdb' in a:
                table = os.path.join(i, a) + '\\DLG元数据'.decode('utf-8')
                metaDataList.append(table)
    fieldsName = []
    cs = arcpy.da.SearchCursor(metaDataList[0], ['*'])
    fl = len(cs.fields)
    i=0
    while i<fl:
        fieldsName.append(cs.fields[i])
        i+=1

    metaDataContentList = []
    for metaData in metaDataList:
        print metaData
        cs = arcpy.da.SearchCursor(metaData, ['*'])
        fl = len(cs.fields)
        med1 = []
        with arcpy.da.SearchCursor(metaData, ['*']) as yb:
            for row in yb:
                i = 0
                while i < fl:
                    med1.append(row[i])
                    i += 1
        metaDataContentList.append(med1)
    df = pd.DataFrame(metaDataContentList,columns=fieldsName)
    df.to_excel(dirPath.decode('utf-8') + '\\' + 'content.xlsx'.decode('utf-8'), index=False)

def closePolyLines(polyling):
    """
    :param polyling: 需要进行封闭的线
    :return: 在该线文件同级目录下生成newLine文件
    """
    arcpy.env.overwriteOutput = True
    filePath = arcpy.Describe(polyling).path
    cs1 = arcpy.da.SearchCursor(polyling, 'SHAPE@')  # 生成游标对象（polyling为两条边线的shape文件）
    lines = [row[0] for row in cs1]  # 生成线列表
    sps = [line.firstPoint for line in lines]  # 生成起点的列表
    eps = [line.lastPoint for line in lines]  # 生成终点的列表
    array = arcpy.Array([point for point in sps])  # 建立起点array
    sl = arcpy.Polyline(array)  # 生成起点polyline对象
    array = arcpy.Array([point for point in eps])  # 建立终点array
    el = arcpy.Polyline(array)  # 生成终点polyline对象
    nl = arcpy.CreateFeatureclass_management(filePath, 'newLine', 'POLYLINE')
    nlcs = arcpy.da.InsertCursor(nl, 'SHAPE@')
    nlcs.insertRow([sl])  # 插入起点线
    nlcs.insertRow([el])  # 插入终点线


def fieldFuncInGDB(pointFile,polygonFile):
    """
    :param pointFile: 点文件
    :param polygonFile: 面文件
    :return: 将点所在的面的字段属性复制到点的相应字段，类似空间连接
    """
    i=1
    cs1 = arcpy.da.UpdateCursor(pointFile, ["SHAPE@","XZQDM","XZQMC"])
    cs2 = arcpy.da.SearchCursor(polygonFile, ["SHAPE@", "XZQDM", "XZQMC"])
    for row1 in cs1:
        for row2 in cs2:
            if row2[0].contains(row1[0]):
                row1[1] = row2[1][0:12]
                row1[2] = row2[2]
                print i, row2[1][0:12], row2[2]
                i += 1
        cs2.reset()
        cs1.updateRow(row1)


def updateByXLSX(xlsx, point):
    import pandas as pd
    """
    :param xlsx: excel表格,表头按a,b,c,d,e,f命名
    :param point: shp点文件
    :return: 根据点文件的'YHMC'字段与表格的'f'字段匹配，将匹配的表格分别填入shp相应字段
    """
    df = pd.read_excel(xlsx)
    i = 1
    with arcpy.da.UpdateCursor(point, ['YHMC', 'GMDJ', 'FXDJ', 'WXRS', 'WXCC', 'BZ']) as yb1:
        for row in yb1:
            for k, v in df.iterrows():
                if row[0] == df.loc[k, 'f']:
                    row[1] = df.loc[k, 'a']
                    row[2] = df.loc[k, 'd']
                    row[3] = df.loc[k, 'b']
                    row[4] = df.loc[k, 'c']
                    row[5] = df.loc[k, 'e']
                    print i, row[0]
                    i += 1
                    yb1.updateRow(row)

def createPointByXLSX(xlFile, fileSavePath,fileName):
    """
    根据xlsx文件（包含x,y）创建点shape文件
    :param xlFile: xlsx文件
    :param fileSavePath: shape文件存储地址
    :param fileName: 保存的文件名称
    :return:
    """
    import pandas as pd
    arcpy.env.overwriteOutput = True
    df = pd.read_excel(xlFile.decode('utf-8'))

    CNList = []
    for index, value in df.iterrows():
        CNList.append(value.values)

    l1 = df.columns.values.tolist()
    l1_Coded = []
    for field in l1:
        l1_Coded.append(field.encode('utf-8'))
    l1_Coded[l1_Coded.index('x')] = 'SHAPE@X'
    l1_Coded[l1_Coded.index('y')] = 'SHAPE@Y'

    l2 = df.columns.values.tolist()
    l2.remove('x')
    l2.remove('y')
    l2_Coded = []
    for field in l2:
        l2_Coded.append(field.encode('utf-8'))

    p = arcpy.CreateFeatureclass_management(fileSavePath, fileName, 'POINT')

    for filed_name in l2_Coded:
        arcpy.AddField_management(p, filed_name, 'TEXT')

    yb = arcpy.da.InsertCursor(p, l1_Coded)

    for CN in CNList:
        yb.insertRow(CN)
    del yb
createPointByXLSX(r'D:\Test\1.xlsx',r'D:\Test','sdz')